<template>
  <q-page class="search-page">
    <!-- 固定搜索栏 -->
    <div class="fixed-search-bar" :class="{ fixed: isScrolled }">
      <div class="fixed-search-container">
        <!-- 登录按钮 -->
        <div class="login-container">
          <q-btn
            label="登录"
            outline
            class="login-button"
            @click="handleLogin"
            v-if="!isLogin"
          />
        </div>

        <!-- 搜索类型选择 -->
        <div class="search-type-selector">
          <div class="search-type-tabs">
            <div
              class="search-tab"
              :class="{ active: searchType === 0 }"
              @click="switchToVideo"
            >
              <q-icon name="video_library" size="20px" />
              <span>视频搜索</span>
            </div>
            <div
              class="search-tab"
              :class="{ active: searchType === 1 }"
              @click="switchToMusic"
            >
              <q-icon name="music_note" size="20px" />
              <span>音乐搜索</span>
            </div>
            <div
              class="search-tab"
              :class="{ active: searchType === 2 }"
              @click="switchToBook"
            >
              <q-icon name="book" size="20px" />
              <span>小说搜索</span>
            </div>
          </div>
        </div>

        <!-- 搜索框 -->
        <div class="search-input-container">
          <q-input
            v-model="searchKeyword"
            placeholder="请输入搜索关键词..."
            outlined
            dense
            class="search-input"
            @keyup.enter="performSearch"
            :disable="!isLogin"
          >
            <template v-slot:append>
              <q-btn
                round
                dense
                flat
                icon="search"
                @click="performSearch"
                :loading="loading"
                :disable="!isLogin"
              />
            </template>
          </q-input>
        </div>
      </div>
    </div>

    <!-- 搜索头部 -->
    <div class="search-header">
      <div class="search-container">
        <!-- 登录按钮 -->
        <div class="login-container">
          <q-btn
            label="登录"
            outline
            class="login-button"
            @click="handleLogin"
            v-if="!isLogin"
          />
        </div>

        <h1 class="search-title">搜索引擎</h1>
        <p class="search-subtitle">支持音乐、视频和小说搜索</p>

        <!-- 搜索类型选择 -->
        <div class="search-type-selector">
          <div class="search-type-tabs">
            <div
              class="search-tab"
              :class="{ active: searchType === 0 }"
              @click="switchToVideo"
            >
              <q-icon name="video_library" size="24px" />
              <span>视频搜索</span>
            </div>
            <div
              class="search-tab"
              :class="{ active: searchType === 1 }"
              @click="switchToMusic"
            >
              <q-icon name="music_note" size="24px" />
              <span>音乐搜索</span>
            </div>
            <div
              class="search-tab"
              :class="{ active: searchType === 2 }"
              @click="switchToBook"
            >
              <q-icon name="book" size="24px" />
              <span>小说搜索</span>
            </div>
          </div>
        </div>

        <!-- 搜索框 -->
        <div class="search-input-container">
          <q-input
            v-model="searchKeyword"
            placeholder="请输入搜索关键词..."
            outlined
            dense
            class="search-input"
            @keyup.enter="performSearch"
            :disable="!isLogin"
          >
            <template v-slot:append>
              <q-btn
                round
                dense
                flat
                icon="search"
                @click="performSearch"
                :loading="loading"
                :disable="!isLogin"
              />
            </template>
          </q-input>
          <div v-if="!isLogin" class="login-prompt">
            <q-icon name="lock" size="16px" />
            <span>请先登录后再进行搜索</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索结果 -->
    <div
      class="search-results"
      v-if="hasVideoResults || hasMusicResults || hasBookResults"
    >
      <div class="results-header">
        <h2>{{ getSearchTypeName() }}搜索结果</h2>
        <q-chip color="primary" text-color="white">
          共找到 {{ currentResults.length }} 个结果
        </q-chip>
      </div>

      <!-- 音乐搜索结果 -->
      <div v-if="searchType === 1" class="music-results">
        <q-card
          v-for="(item, index) in musicResults"
          :key="index"
          class="music-card q-mb-md"
          flat
          bordered
        >
          <q-card-section horizontal>
            <q-card-section class="music-cover">
              <q-img
                :src="
                  item.cover ||
                  'https://via.placeholder.com/80x80?text=No+Cover'
                "
                width="80px"
                height="80px"
                fit="cover"
                class="rounded-borders"
              />
            </q-card-section>

            <q-card-section class="music-info">
              <div class="text-h6 text-weight-bold">{{ item.song }}</div>
              <div class="text-subtitle2 text-grey-7">{{ item.singer }}</div>
              <div class="text-caption text-grey-6">{{ item.album }}</div>
              <div class="music-meta">
                <q-chip
                  :label="item.type === 'tencent' ? '腾讯音乐' : '网易云音乐'"
                  :color="item.type === 'tencent' ? 'green' : 'red'"
                  text-color="white"
                  size="sm"
                />
                <q-chip
                  v-if="item.quality"
                  :label="item.quality"
                  color="blue"
                  text-color="white"
                  size="sm"
                />
                <q-chip
                  v-if="item.time"
                  :label="item.time"
                  color="grey"
                  text-color="white"
                  size="sm"
                />
              </div>
              <div class="music-actions q-mt-sm">
                <q-btn
                  :label="item.showDetail ? '收起详情' : '查看详情'"
                  :icon="item.showDetail ? 'expand_less' : 'expand_more'"
                  color="primary"
                  outline
                  size="sm"
                  @click="toggleMusicDetail(item, index)"
                  :loading="item.loadingDetail"
                />
              </div>
            </q-card-section>
          </q-card-section>

          <!-- 音乐详情展开区域 -->
          <q-slide-transition>
            <div v-show="item.showDetail" class="music-detail">
              <q-separator />
              <q-card-section class="detail-content">
                <div v-if="item.detailLoading" class="text-center q-pa-md">
                  <q-spinner color="primary" size="2em" />
                  <div class="text-caption q-mt-sm">加载中...</div>
                </div>

                <div v-else-if="item.detailError" class="text-center q-pa-md">
                  <q-icon name="error" color="red" size="2em" />
                  <div class="text-caption q-mt-sm text-red">
                    {{ item.detailError }}
                  </div>
                </div>

                <div v-else-if="item.detail" class="detail-info">
                  <!-- 基本信息 -->
                  <div class="detail-section">
                    <h4 class="text-h6 q-mb-md">基本信息</h4>
                    <div class="detail-grid">
                      <div class="detail-item">
                        <span class="label">歌曲：</span>
                        <span class="value">{{ item.detail.song }}</span>
                      </div>
                      <div class="detail-item">
                        <span class="label">歌手：</span>
                        <span class="value">{{ item.detail.singer }}</span>
                      </div>
                      <div class="detail-item">
                        <span class="label">专辑：</span>
                        <span class="value">{{ item.detail.album }}</span>
                      </div>
                      <div class="detail-item">
                        <span class="label">时长：</span>
                        <span class="value">{{ item.detail.interval }}</span>
                      </div>
                      <div class="detail-item">
                        <span class="label">音质：</span>
                        <span class="value">{{ item.detail.quality }}</span>
                      </div>
                      <div class="detail-item">
                        <span class="label">大小：</span>
                        <span class="value">{{ item.detail.size }}</span>
                      </div>
                      <div class="detail-item">
                        <span class="label">BPM：</span>
                        <span class="value">{{ item.detail.bpm }}</span>
                      </div>
                      <div class="detail-item">
                        <span class="label">发布时间：</span>
                        <span class="value">{{ item.detail.time }}</span>
                      </div>
                    </div>
                  </div>

                  <!-- 操作按钮 -->
                  <div class="detail-section">
                    <h4 class="text-h6 q-mb-md">操作</h4>
                    <div class="action-buttons">
                      <q-btn
                        label="下载音乐"
                        icon="download"
                        color="primary"
                        @click="downloadMusic(item.detail)"
                        :disable="!item.detail.url"
                      />
                      <q-btn
                        label="下载歌词"
                        icon="description"
                        color="secondary"
                        @click="downloadLyrics(item.detail)"
                        :disable="!item.detail.lrc?.lrc"
                      />
                      <q-btn
                        label="平台链接"
                        icon="link"
                        color="green"
                        @click="playMusic(item.detail)"
                        :disable="!item.detail.link"
                      />
                      <q-btn
                        label="在线播放"
                        icon="play_arrow"
                        color="green"
                        @click="playMusicOnline(item.detail)"
                        :disable="!item.detail.link"
                      />
                    </div>
                  </div>

                  <!-- 歌词预览 -->
                  <div v-if="item.detail.lrc?.lrc" class="detail-section">
                    <h4 class="text-h6 q-mb-md">歌词预览</h4>
                    <div class="lyrics-preview">
                      <pre class="lyrics-text">{{
                        formatLyrics(item.detail.lrc.lrc)
                      }}</pre>
                    </div>
                  </div>
                </div>
              </q-card-section>
            </div>
          </q-slide-transition>
        </q-card>
      </div>

      <!-- 小说搜索结果 -->
      <div v-else-if="searchType === 2" class="book-results">
        <q-card
          v-for="(item, index) in bookResults"
          :key="index"
          class="book-card q-mb-md"
          flat
          bordered
        >
          <q-card-section horizontal>
            <q-card-section class="book-cover">
              <q-img
                :src="
                  item.cover ||
                  'https://via.placeholder.com/80x120?text=No+Cover'
                "
                width="80px"
                height="120px"
                fit="cover"
                class="rounded-borders"
              />
            </q-card-section>

            <q-card-section class="book-info">
              <div class="text-h6 text-weight-bold">{{ item.title }}</div>
              <div class="text-subtitle2 text-grey-7">
                作者：{{ item.author }}
              </div>
              <div class="text-caption text-grey-6">{{ item.status }}</div>
              <div class="book-meta">
                <q-chip
                  v-if="item.read_count"
                  :label="item.read_count"
                  color="blue"
                  text-color="white"
                  size="sm"
                />
                <q-chip
                  v-if="item.update_time"
                  :label="item.update_time"
                  color="green"
                  text-color="white"
                  size="sm"
                />
              </div>
              <div class="book-chapters q-mt-sm">
                <div class="text-caption text-grey-6">最新章节：</div>
                <div class="chapter-list">
                  <span
                    v-for="(chapter, chapterIndex) in item.chapter_list"
                    :key="chapterIndex"
                    class="chapter-item"
                  >
                    {{ chapter }}
                    <span v-if="chapterIndex < item.chapter_list.length - 1"
                      >,
                    </span>
                  </span>
                </div>
              </div>
              <div class="book-actions q-mt-sm">
                <q-btn
                  :label="item.showDetail ? '收起详情' : '查看详情'"
                  :icon="item.showDetail ? 'expand_less' : 'expand_more'"
                  color="primary"
                  outline
                  size="sm"
                  @click="toggleBookDetail(item, index)"
                  :loading="item.loadingDetail"
                />
              </div>
            </q-card-section>
          </q-card-section>

          <!-- 小说详情展开区域 -->
          <q-slide-transition>
            <div v-show="item.showDetail" class="book-detail">
              <q-separator />
              <q-card-section class="detail-content">
                <div v-if="item.detailLoading" class="text-center q-pa-md">
                  <q-spinner color="primary" size="2em" />
                  <div class="text-caption q-mt-sm">加载中...</div>
                </div>

                <div v-else-if="item.detailError" class="text-center q-pa-md">
                  <q-icon name="error" color="red" size="2em" />
                  <div class="text-caption q-mt-sm text-red">
                    {{ item.detailError }}
                  </div>
                </div>

                <div v-else-if="item.detail" class="detail-info">
                  <!-- 基本信息 -->
                  <div class="detail-section">
                    <h4 class="text-h6 q-mb-md">基本信息</h4>
                    <div class="detail-grid">
                      <div class="detail-item">
                        <span class="label">书名：</span>
                        <span class="value">{{ item.detail.title }}</span>
                      </div>
                      <div class="detail-item">
                        <span class="label">作者：</span>
                        <span class="value">{{ item.detail.author }}</span>
                      </div>
                      <div class="detail-item">
                        <span class="label">状态：</span>
                        <span class="value">{{ item.detail.status }}</span>
                      </div>
                      <div class="detail-item">
                        <span class="label">阅读量：</span>
                        <span class="value">{{ item.detail.read_count }}</span>
                      </div>
                      <div class="detail-item">
                        <span class="label">更新时间：</span>
                        <span class="value">{{ item.detail.update_time }}</span>
                      </div>
                    </div>
                  </div>

                  <!-- 小说简介 -->
                  <div v-if="item.detail.description" class="detail-section">
                    <h4 class="text-h6 q-mb-md">小说简介</h4>
                    <div class="book-description">
                      <p>{{ item.detail.description }}</p>
                    </div>
                  </div>

                  <!-- 章节列表 -->
                  <div
                    v-if="
                      item.detail.chapter_list &&
                      item.detail.chapter_list.length > 0
                    "
                    class="detail-section"
                  >
                    <h4 class="text-h6 q-mb-md">章节列表</h4>
                    <div class="chapter-list-detail">
                      <div
                        v-for="(chapter, chapterIndex) in item.detail
                          .chapter_list"
                        :key="chapterIndex"
                        class="chapter-item-detail"
                      >
                        {{ chapter }}
                      </div>
                    </div>
                  </div>

                  <!-- 下载链接 -->
                  <div
                    v-if="
                      item.detail.download_list &&
                      item.detail.download_list.length > 0
                    "
                    class="detail-section"
                  >
                    <h4 class="text-h6 q-mb-md">下载链接</h4>
                    <div class="download-list">
                      <q-btn
                        v-for="(download, downloadIndex) in item.detail
                          .download_list"
                        :key="downloadIndex"
                        :label="download.title"
                        icon="download"
                        color="primary"
                        @click="downloadBook(download)"
                        class="q-mr-sm q-mb-sm"
                      />
                    </div>
                  </div>
                </div>
              </q-card-section>
            </div>
          </q-slide-transition>
        </q-card>
      </div>

      <!-- 视频搜索结果 -->
      <div v-else class="video-results">
        <q-card
          v-for="(item, index) in videoResults"
          :key="index"
          class="video-card q-mb-md"
          flat
          bordered
        >
          <q-card-section>
            <div class="video-header">
              <div class="text-h6 text-weight-bold">
                {{ item.question || item.ID }}
              </div>
              <q-chip
                v-if="item.isTop"
                label="置顶"
                color="red"
                text-color="white"
                size="sm"
              />
            </div>

            <div class="video-content q-mt-md">
              <div class="text-body2" v-html="item.answer"></div>
            </div>

            <!-- HTTP链接提取和复制 -->
            <div
              v-if="extractHttpLinks(item.answer).length > 0"
              class="http-links-section q-mt-md"
            >
              <div class="links-header">
                <q-icon name="link" size="16px" color="primary" />
                <span class="text-subtitle2 text-weight-medium"
                  >提取到的链接</span
                >
              </div>
              <div class="links-list">
                <div
                  v-for="(link, linkIndex) in extractHttpLinks(item.answer)"
                  :key="linkIndex"
                  class="link-item"
                >
                  <div class="link-text">{{ link }}</div>
                  <q-btn
                    label="复制链接"
                    icon="content_copy"
                    color="primary"
                    size="sm"
                    outline
                    @click="copyToClipboard(link)"
                  />
                </div>
              </div>
            </div>

            <div v-if="item.bd_pic" class="video-image q-mt-md">
              <q-img
                :src="item.bd_pic"
                width="200px"
                height="120px"
                fit="cover"
                class="rounded-borders"
              />
            </div>

            <div class="video-meta q-mt-md">
              <q-chip
                v-if="item.res_platform"
                :label="item.res_platform"
                color="purple"
                text-color="white"
                size="sm"
              />
              <q-chip
                v-if="item.ID"
                :label="`ID: ${item.ID}`"
                color="grey"
                text-color="white"
                size="sm"
              />
            </div>
          </q-card-section>
        </q-card>
      </div>
    </div>

    <!-- 错误提示 -->
    <div v-if="currentError" class="error-container">
      <q-banner class="bg-red text-white">
        <template v-slot:avatar>
          <q-icon name="error" />
        </template>
        搜索失败: {{ currentError }}
      </q-banner>
    </div>

    <!-- 初始状态提示 -->
    <div
      v-if="
        !loading &&
        !currentHasSearched &&
        !currentError &&
        currentResults.length === 0
      "
      class="initial-state"
    >
      <q-icon name="search" size="64px" color="grey-5" />
      <div class="text-h6 text-grey-6 q-mt-md">
        现在，{{ getSearchTypeName() }}列表空空如也
      </div>
      <div class="text-caption text-grey-5">在上方键入关键词搜索吧！</div>
    </div>

    <!-- 空状态 -->
    <div
      v-if="
        !loading &&
        currentHasSearched &&
        !currentError &&
        currentResults.length === 0
      "
      class="empty-state"
    >
      <q-icon name="search_off" size="64px" color="grey-5" />
      <div class="text-h6 text-grey-6 q-mt-md">未找到相关结果</div>
      <div class="text-caption text-grey-5">请尝试其他关键词</div>
    </div>
  </q-page>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import { useQuasar } from "quasar";
import { useRoute } from "vue-router";
import { searchAPI } from "src/boot/axios";
import { isLogin, OpenNewTab, Dialog } from "src/js/common";

defineOptions({
  name: "IndexPage",
});

const $q = useQuasar();
const route = useRoute();

// 响应式数据
const searchType = ref(0); // 0: 视频, 1: 音乐, 2: 小说
const searchKeyword = ref("");
const videoResults = ref([]);
const musicResults = ref([]);
const bookResults = ref([]);
const loading = ref(false);
const videoError = ref("");
const musicError = ref("");
const bookError = ref("");
const hasVideoSearched = ref(false);
const hasMusicSearched = ref(false);
const hasBookSearched = ref(false);
const isScrolled = ref(false);

// 计算属性
const hasVideoResults = computed(() => {
  return videoResults.value && videoResults.value.length > 0;
});

const hasMusicResults = computed(() => {
  return musicResults.value && musicResults.value.length > 0;
});

const hasBookResults = computed(() => {
  return bookResults.value && bookResults.value.length > 0;
});

const currentResults = computed(() => {
  if (searchType.value === 0) return videoResults.value;
  if (searchType.value === 1) return musicResults.value;
  return bookResults.value;
});

const currentError = computed(() => {
  if (searchType.value === 0) return videoError.value;
  if (searchType.value === 1) return musicError.value;
  return bookError.value;
});

const currentHasSearched = computed(() => {
  if (searchType.value === 0) return hasVideoSearched.value;
  if (searchType.value === 1) return hasMusicSearched.value;
  return hasBookSearched.value;
});

// 登录处理
const handleLogin = () => {
  const encode = encodeURIComponent;
  window.location.href = `https://login.zhuchundashuaige.com/#/?RedirectUri=${encode(
    "http://" + window.location.host
  )}&Type=SPA`;
};

// 切换到视频搜索
const switchToVideo = () => {
  searchType.value = 0;
};

// 切换到音乐搜索
const switchToMusic = () => {
  searchType.value = 1;
};

// 切换到小说搜索
const switchToBook = () => {
  searchType.value = 2;
};

// 滚动监听
const handleScroll = () => {
  // 在移动端始终显示悬浮搜索栏
  if (window.innerWidth <= 768) {
    isScrolled.value = true;
  } else {
    isScrolled.value = window.scrollY > 200;
  }
};

// 组件挂载时添加滚动监听
onMounted(() => {
  window.addEventListener("scroll", handleScroll);
  // 初始化移动端状态
  handleScroll();

  // 根据路由参数切换tab
  const type = route.query.type;
  if (type === "music") {
    searchType.value = 1;
  } else if (type === "book") {
    searchType.value = 2;
  } else if (type === "video") {
    searchType.value = 0;
  }
});

// 组件卸载时移除滚动监听
onUnmounted(() => {
  window.removeEventListener("scroll", handleScroll);
});

// 获取搜索类型名称
const getSearchTypeName = () => {
  if (searchType.value === 0) return "视频";
  if (searchType.value === 1) return "音乐";
  return "小说";
};

// 执行搜索
const performSearch = async () => {
  if (!isLogin) {
    $q.notify({
      type: "warning",
      message: "请先登录后再进行搜索",
    });
    return;
  }

  if (!searchKeyword.value.trim()) {
    $q.notify({
      type: "warning",
      message: "请输入搜索关键词",
    });
    return;
  }

  loading.value = true;

  try {
    let response;
    if (searchType.value === 1) {
      // 音乐搜索
      musicError.value = "";
      hasMusicSearched.value = true;
      response = await searchAPI.searchMusic(searchKeyword.value);

      if (response && response.data) {
        musicResults.value = Array.isArray(response.data)
          ? response.data
          : [response.data];
      } else {
        musicResults.value = [];
      }
    } else if (searchType.value === 2) {
      // 小说搜索
      bookError.value = "";
      hasBookSearched.value = true;
      response = await searchAPI.searchBook(searchKeyword.value);

      if (response && response.data) {
        bookResults.value = Array.isArray(response.data)
          ? response.data
          : [response.data];
      } else {
        bookResults.value = [];
      }
    } else {
      // 视频搜索
      videoError.value = "";
      hasVideoSearched.value = true;
      response = await searchAPI.searchVideo(searchKeyword.value);

      if (response && response.data) {
        videoResults.value = Array.isArray(response.data)
          ? response.data
          : [response.data];
      } else {
        videoResults.value = [];
      }
    }
  } catch (err) {
    console.error("搜索失败:", err);

    // 处理403错误，将登录状态设置为false
    if (err.response && err.response.status === 403) {
      isLogin.value = false;
      const errorMessage = "登录已过期，请重新登录";
      if (searchType.value === 1) {
        musicError.value = errorMessage;
      } else if (searchType.value === 2) {
        bookError.value = errorMessage;
      } else {
        videoError.value = errorMessage;
      }
      $q.notify({
        type: "warning",
        message: "登录已过期，请重新登录",
      });
    } else {
      // 尝试解析其他错误信息
      const errorMessage =
        err.response && err.response.data
          ? err.response.data.error || err.response.data.message || "请求失败"
          : err.message || "网络错误，请稍后重试";

      if (searchType.value === 1) {
        musicError.value = errorMessage;
        musicResults.value = [];
      } else if (searchType.value === 2) {
        bookError.value = errorMessage;
        bookResults.value = [];
      } else {
        videoError.value = errorMessage;
        videoResults.value = [];
      }
    }
  } finally {
    loading.value = false;
  }
};

// 格式化视频答案（处理链接）
const formatVideoAnswer = (answer) => {
  if (!answer) return "";

  return answer;
};

// 切换音乐详情显示
const toggleMusicDetail = async (item, index) => {
  if (item.showDetail) {
    // 收起详情
    item.showDetail = false;
  } else {
    // 展开详情
    item.showDetail = true;
    item.loadingDetail = true;
    item.detailLoading = true;
    item.detailError = "";

    try {
      const response = await searchAPI.getMusicDetail(
        searchKeyword.value,
        item.id
      );
      if (response && response.data) {
        musicResults.value[index].detail = response.data;
      } else {
        item.detailError = "获取详情失败";
      }
    } catch (err) {
      console.error("获取音乐详情失败:", err);
      item.detailError =
        err.response?.data?.error || err.message || "获取详情失败";
    } finally {
      item.loadingDetail = false;
      item.detailLoading = false;
    }
  }
};

// 下载音乐
const downloadMusic = (detail) => {
  if (detail.url) {
    const link = document.createElement("a");
    link.href = detail.url;
    link.download = `${detail.singer} - ${detail.song}.mp3`;
    link.target = "_blank";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    $q.notify({
      type: "positive",
      message: "开始下载音乐",
    });
  }
};

// 下载歌词
const downloadLyrics = (detail) => {
  if (detail.lrc?.lrc) {
    const lyrics = formatLyrics(detail.lrc.lrc);
    const blob = new Blob([lyrics], { type: "text/plain;charset=utf-8" });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = `${detail.singer} - ${detail.song}.lrc`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);

    $q.notify({
      type: "positive",
      message: "歌词下载成功",
    });
  }
};

// 在线播放
const playMusic = (detail) => {
  if (detail.link) {
    window.open(detail.link, "_blank");
  }
};

const playMusicOnline = (detail) => {
  // 判断是否在iframe中
  if (window.self !== window.top) {
    // 在iframe中，向父窗口发送消息
    // 只传递可序列化的数据，避免DataCloneError
    const serializableDetail = {
      id: detail.id,
      url: detail.url,
      link: detail.link,
      song: detail.song,
      singer: detail.singer,
      album: detail.album,
      quality: detail.quality,
      time: detail.time,
      interval: detail.interval,
      size: detail.size,
      bpm: detail.bpm,
    };

    window.parent.postMessage(
      {
        type: "playMusicOnline",
        detail: serializableDetail,
      },
      "*"
    );
  } else {
    // 不在iframe中，使用Quasar dialog展示iframe
    let host = "https://music.zhuchundashuaige.com";
    if (localStorage.getItem("host")) {
      host = localStorage.getItem("host");
    }
    let url = "";
    if (detail.id) {
      url = `${host}/#/?id=${detail.id}`;
    } else if (detail.url) {
      url = `${host}/#/?url=${detail.url}`;
    }
    if (url) {
      Dialog(url, "在线音乐播放");
    }
  }
};

// 格式化歌词
const formatLyrics = (lrcText) => {
  if (!lrcText) return "";

  // 移除时间标签，只保留歌词文本
  return lrcText
    .replace(/\[\d{2}:\d{2}\.\d{2}\]/g, "") // 移除时间标签
    .replace(/\[ti:.*?\]/g, "") // 移除标题标签
    .replace(/\[ar:.*?\]/g, "") // 移除艺术家标签
    .replace(/\[al:.*?\]/g, "") // 移除专辑标签
    .replace(/\[by:.*?\]/g, "") // 移除制作者标签
    .replace(/\[offset:.*?\]/g, "") // 移除偏移标签
    .trim();
};

// 切换小说详情显示
const toggleBookDetail = async (item, index) => {
  if (item.showDetail) {
    // 收起详情
    item.showDetail = false;
  } else {
    // 展开详情
    item.showDetail = true;
    item.loadingDetail = true;
    item.detailLoading = true;
    item.detailError = "";

    try {
      const response = await searchAPI.getBookDetail(
        searchKeyword.value,
        item.id
      );
      if (response && response.data) {
        bookResults.value[index].detail = response.data;
      } else {
        item.detailError = "获取详情失败";
      }
    } catch (err) {
      console.error("获取小说详情失败:", err);
      item.detailError =
        err.response?.data?.error || err.message || "获取详情失败";
    } finally {
      item.loadingDetail = false;
      item.detailLoading = false;
    }
  }
};

// 下载小说
const downloadBook = (download) => {
  if (download.downloadUrl) {
    window.open(download.downloadUrl, "_blank");

    $q.notify({
      type: "positive",
      message: "开始下载小说",
    });
  }
};

// 提取HTTP链接
const extractHttpLinks = (text) => {
  if (!text) return [];

  // 匹配http或https链接的正则表达式
  const httpRegex = /https?:\/\/[^\s<>"']+/g;
  const matches = text.match(httpRegex);

  if (!matches) return [];

  // 去重并返回
  return [...new Set(matches)];
};

// 复制到剪贴板
const copyToClipboard = async (text) => {
  try {
    await navigator.clipboard.writeText(text);
    $q.notify({
      type: "positive",
      message: "链接已复制到剪贴板",
      position: "top",
      timeout: 2000,
    });
  } catch (err) {
    // 降级方案：使用传统方法
    const textArea = document.createElement("textarea");
    textArea.value = text;
    document.body.appendChild(textArea);
    textArea.select();
    document.execCommand("copy");
    document.body.removeChild(textArea);

    $q.notify({
      type: "positive",
      message: "链接已复制到剪贴板",
      position: "top",
      timeout: 2000,
    });
  }
};
</script>

<style lang="scss" scoped>
.search-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.fixed-search-bar {
  position: fixed;
  top: -100px;
  left: 0;
  right: 0;
  z-index: 1000;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
  transition: top 0.3s ease;
  padding: 10px 20px;

  &.fixed {
    top: 0;
  }

  // 在移动端始终显示
  @media (max-width: 768px) {
    top: 0;
  }
}

.fixed-search-container {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  gap: 20px;
  justify-content: space-between;
}

.fixed-search-container .login-container {
  position: static;
  flex-shrink: 0;
}

.fixed-search-container .search-type-selector {
  margin: 0;
  flex-shrink: 0;
}

.fixed-search-container .search-type-tabs {
  max-width: 400px;
  background: rgba(102, 126, 234, 0.1);
  border: 1px solid rgba(102, 126, 234, 0.2);
}

.fixed-search-container .search-tab {
  color: #667eea;
  font-size: 12px;
  padding: 8px 16px;

  &:hover {
    background: rgba(102, 126, 234, 0.1);
  }

  &.active {
    background: #667eea;
    color: white;
  }
}

.fixed-search-container .search-input-container {
  flex: 1;
  max-width: 400px;
  margin: 0;
}

.fixed-search-container .search-input {
  background: white;
}

.search-header {
  padding: 60px 20px 40px;
  text-align: center;
  color: white;
}

.search-container {
  max-width: 600px;
  margin: 0 auto;
  position: relative;
}

.login-container {
  position: absolute;
  top: -40px;
  right: 0;
}

.login-button {
  border-radius: 20px;
  font-weight: 500;
  padding: 8px 20px;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  }
}

.search-title {
  font-size: 2.5rem;
  font-weight: 700;
  margin: 0 0 10px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.search-subtitle {
  font-size: 1.1rem;
  margin: 0 0 30px 0;
  opacity: 0.9;
}

.search-type-selector {
  margin-bottom: 30px;
}

.search-type-tabs {
  display: flex;
  justify-content: center;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 25px;
  padding: 4px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  max-width: 400px;
  margin: 0 auto;
}

.search-tab {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  color: rgba(255, 255, 255, 0.8);
  font-weight: 500;
  flex: 1;
  justify-content: center;

  &:hover {
    background: rgba(255, 255, 255, 0.1);
    color: white;
  }

  &.active {
    background: white;
    color: #667eea;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  span {
    font-size: 14px;
  }
}

.search-input-container {
  max-width: 500px;
  margin: 0 auto;
  position: relative;
}

.search-input {
  background: white;
  border-radius: 25px;

  :deep(.q-field__control) {
    border-radius: 25px;
  }
}

.login-prompt {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: center;
  margin-top: 12px;
  color: rgba(255, 255, 255, 0.9);
  font-size: 14px;
  background: rgba(255, 255, 255, 0.1);
  padding: 8px 16px;
  border-radius: 20px;
  backdrop-filter: blur(10px);
}

.search-results {
  padding: 40px 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 0 10px;

  h2 {
    margin: 0;
    color: #333;
    font-size: 1.5rem;
    font-weight: 600;
    letter-spacing: 0.5px;
  }
}

.music-card {
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
}

.music-cover {
  padding: 16px;
}

.music-info {
  flex: 1;
  padding: 16px 16px 16px 0;
}

.music-meta {
  margin-top: 8px;

  .q-chip {
    margin-right: 8px;
    margin-bottom: 4px;
  }
}

.music-actions {
  margin-top: 12px;
}

.music-detail {
  background: #f8f9fa;
}

.detail-content {
  padding: 20px;
}

.detail-section {
  margin-bottom: 24px;

  &:last-child {
    margin-bottom: 0;
  }
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 12px;
}

.detail-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background: white;
  border-radius: 8px;
  border: 1px solid #e0e0e0;

  .label {
    font-weight: 600;
    color: #666;
    min-width: 80px;
    margin-right: 8px;
  }

  .value {
    color: #333;
    flex: 1;
  }
}

.action-buttons {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.lyrics-preview {
  background: white;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 16px;
  max-height: 300px;
  overflow-y: auto;
}

.lyrics-text {
  font-family: "Courier New", monospace;
  font-size: 14px;
  line-height: 1.6;
  color: #333;
  margin: 0;
  white-space: pre-wrap;
  word-break: break-word;
}

.video-card {
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
}

.video-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.video-content {
  line-height: 1.6;

  :deep(a) {
    text-decoration: none;

    &:hover {
      text-decoration: underline;
    }
  }
}

.video-meta {
  .q-chip {
    margin-right: 8px;
    margin-bottom: 4px;
  }
}

.http-links-section {
  background: #f8f9fa;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 16px;
}

.links-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  color: #333;
}

.links-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.link-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  padding: 12px;
  transition: all 0.2s ease;

  &:hover {
    border-color: #667eea;
    box-shadow: 0 2px 4px rgba(102, 126, 234, 0.1);
  }
}

.link-text {
  flex: 1;
  font-family: "Courier New", monospace;
  font-size: 12px;
  color: #666;
  word-break: break-all;
  margin-right: 12px;
  line-height: 1.4;
}

.book-card {
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
}

.book-cover {
  padding: 16px;
}

.book-info {
  flex: 1;
  padding: 16px 16px 16px 0;
}

.book-meta {
  margin-top: 8px;

  .q-chip {
    margin-right: 8px;
    margin-bottom: 4px;
  }
}

.book-chapters {
  .chapter-list {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
  }

  .chapter-item {
    color: #666;
    font-size: 12px;
  }
}

.book-actions {
  margin-top: 12px;
}

.book-detail {
  background: #f8f9fa;
}

.book-description {
  background: white;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 16px;
  line-height: 1.6;
  color: #333;
}

.chapter-list-detail {
  background: white;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 16px;
  max-height: 300px;
  overflow-y: auto;
}

.chapter-item-detail {
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
  color: #333;
  font-size: 14px;

  &:last-child {
    border-bottom: none;
  }
}

.download-list {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.error-container {
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
}

.initial-state {
  text-align: center;
  padding: 80px 20px;
  color: #666;
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
  color: #666;
}

@media (max-width: 768px) {
  .search-title {
    font-size: 2rem;
  }

  .search-results {
    padding: 20px 10px;
  }

  .results-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }

  .fixed-search-container .search-type-tabs {
    max-width: 300px;
  }

  .search-type-tabs {
    flex-direction: column;
    gap: 4px;
  }

  .search-tab {
    font-size: 12px;
    padding: 8px 12px;
  }

  // 在移动端隐藏正常搜索栏，只显示悬浮搜索栏
  .search-header {
    display: none;
  }

  // 调整搜索结果的上边距，因为没有了正常搜索栏
  .search-results {
    padding-top: 20px;
  }

  // 确保悬浮搜索栏在移动端正确显示
  .fixed-search-bar {
    padding: 8px 15px;
  }

  .fixed-search-container {
    gap: 10px;
  }

  .fixed-search-container .search-type-tabs {
    max-width: 200px;
  }

  .fixed-search-container .search-tab {
    font-size: 10px;
    padding: 6px 10px;
  }

  .fixed-search-container .search-tab span {
    display: none;
  }
}
</style>
